/*****************************************************************************
	SNEGA UTILITIES 0.7a
	Copyright (C) 2009, Xiaohan Tian (snega0223)
	
	http://code.google.com/p/snega-utilities/
	
	This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License(LGPL) as
	published by the Free Software Foundation, either version 3 of the 
	License, or(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Lesser General Public License for more details.
	
	You should have received a copy of the GNU Lesser General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/

package org.sng.util.web;

import java.util.*;

import javax.servlet.http.*;

import org.sng.util.web.elmt.*;

public class WebPageMaker {
	
	protected HashMap<String, Node> m_factory;
	
	public WebPageMaker()
	{
		this.m_factory = new HashMap<String, Node>();
		
		DefaultNodeFactory.CreateDefaultNodeFactory(this.m_factory);
	}
	
	public String uuid()
	{
		return UUID.randomUUID().toString().replace("-", "_");
	}
	
	public void AddWorker(String key, Node o)
	{
		this.m_factory.put(key, o);
	}
	
	public Node CreateNode(String id)
	{
		return this.m_factory.get(id.toLowerCase()).Create();
	}
	
	public Node CreateNode(String id, int n)
	{
		return this.m_factory.get(id.toLowerCase()).Create(n);
	}
	
	public Node CreateNode(String type, String id, RuntimeEnvironment re)
	{
		return this.m_factory.get(type.toLowerCase()).Create(id, re);
	}
	
	public int Make(RuntimeEnvironment re)
	{
		re.Out(re.GetRoot().Execute(re).toString());
		
		// Build container relationship in "NodeEndBody"
		
		return MakeResult.SUCCESS;
	}
	
	public int Process(RuntimeEnvironment re, HttpServletRequest request)
	{
		// Rebuild nodes
		String [] ids = request.getParameterValues("cid");
		String [] types = request.getParameterValues("type");
		
		for (int i = 0; i < ids.length; i++)
		{
			Node o = this.CreateNode(types[i], ids[i], re);
			
			re.GetRoot().AddChild(o);
			re.GetRoot().AddNodeToIdMap(ids[i], o);
			re.GetRoot().AddNodeToTypeList(types[i], o);
			
			o.AppendPostList(re);		// For already exist element, just re-call the AppendPostList method, for new element, just call Execute method which can append post-list automatically.
		}
		
		// Rebuild container relationship
		Node [] o = re.GetRoot().GetNodeArrayByType("container");
		for (int i = 0; o != null && i < o.length; i++)
		{
			((NodeContainer)(o[i])).RegisterChildren(re);
		}
		
		return MakeResult.SUCCESS;
	}

}
